<template>
  <div>
    <a-drawer
      title="编辑"
      placement="right"
      :closable="false"
      :visible="visible"
      @close="onClose"
      :destroyOnClose="true"
      :width="800"
      :headerStyle="{ position: 'fixed', top: 0, width: '100%', background: '#fff', zIndex: 2 }"
      :body-style="{ paddingBottom: '80px', paddingTop: '80px' }"
    >
      <a-form-model ref="ruleForm" :model="form" :label-col="labelCol" :wrapper-col="wrapperCol" :rules="rules">
        <a-form-model-item label="内部名称" prop="innerName">
          <a-input v-model="form.innerName" />
        </a-form-model-item>
        <a-form-model-item label="对外展示名称" prop="name">
          <a-input v-model="form.name" />
        </a-form-model-item>
        <a-form-model-item label="发放类型" prop="type">
          <a-select v-model="form.type" placeholder="please select your zone">
            <a-select-option :value="0">
              自动发放
            </a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item label="发放时间" prop="sendTime">
          <a-date-picker v-model="form.sendTime" :show-time="{ defaultValue: moment('00:00:00', 'HH:mm:ss') }" type="date" placeholder="请选择日期" style="width: 100%;" />
        </a-form-model-item>
        <a-form-model-item label="通知" prop="noticeType">
          <a-select v-model="form.noticeType" placeholder="please select your zone">
            <a-select-option :value="0">
              不通知
            </a-select-option>
            <a-select-option :value="1">
              短信
            </a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item label="短信模板" v-if="form.noticeType == 1">
          <a-input v-model="sms" type="textarea" :rows="4" disabled />
          <div>1.不超过65个字；2.只有报备过的短信模板才能发送</div>
        </a-form-model-item>
        <a-form-model-item label="发放用户" prop="sendType">
          <a-select v-model="form.sendType" placeholder="please select your zone">
            <a-select-option :value="1">
              部分用户
            </a-select-option>
          </a-select>
          <div style="margin-top:12px">
            <a download :href="file" style="margin-right:12px">导出用户模板</a>

            <a-upload
              name="file"
              :multiple="false"
              accept=".xls,.xlsx"
              :action="uploadParams.actionUrl"
              :headers="uploadParams.headers"
              :data="formKeyData"
              :fileList="fileList"
              :remove="handleRemove"
              :beforeUpload="beforeUpload"
              @change="handleChange"
            >
              <a-button type="primary">导入</a-button>
            </a-upload>
            <p class="tip" v-if="showTipClient" style="margin-bottom:0;">请导入</p>
          </div>
        </a-form-model-item>
        <a-form-model-item label="优惠券选择" required>
          <a-button type="primary" @click="openCoupons"><a-icon type="plus" />添加</a-button>
        </a-form-model-item>
        <div style="margin-bottom:24px">
          <a-table style="margin-top: 20px;" :rowKey="record => JSON.stringify(record)" :columns="columns" :data-source="couponsList" :pagination="false">
            <span slot="action" slot-scope="text, record, index">
              <template>
                <a @click="handleDeleteProduct(index)">删除</a>
              </template>
            </span>
          </a-table>
          <p class="tip" style="" v-if="showTip">请选择优惠券！</p>
        </div>
        <a-form-model-item :wrapper-col="{ span: 14, offset: 4 }">
          <a-button type="primary" @click="onSubmit">保存</a-button>
          <a-button style="margin-left: 10px;" @click="onClose">取消</a-button>
        </a-form-model-item>
      </a-form-model>
    </a-drawer>
    <CouponModal ref="couponModal" @handleAddCoupons="handleAddCoupons"></CouponModal>
  </div>
</template>
<script>
import moment from 'moment'
import globalData from '@/assets/js/common'
import { createSendCoupon, couponList } from '@/api/box/setting'
import { CouponModal } from '@/views/box/components'
import { uploadToken } from '@/api/api'
const columns = [
  { title: '序号', width: 60, customRender: (text, record, index) => `${index + 1}` },
  { title: '券名称', dataIndex: 'name' },
  { title: '券类型', dataIndex: 'type', customRender: text => (text == 1 ? '折扣券' : text == 0 ? '现金券' : '') },
  { title: '面额', customRender: (text, record) => (record.type == 1 ? record.discount * 100 + '%' : record.type == 0 ? record.amount + '元' : '') },
  { title: '有效期类型', dataIndex: 'expireType', align: 'center', customRender: text => (text == 1 ? '按领取时间顺延' : '指定时间') },
  { title: '有效期', align: 'center', customRender: (text, record) => (record.expireType == 1 ? record.endDays + '天' : record.expireType == 0 ? `${record.startDate}-${record.endDate}` : '') },
  { title: '操作', fixed: 'right', width: 60, align: 'center', scopedSlots: { customRender: 'action' } }
]
export default {
  components: { CouponModal },
  data() {
    return {
      moment,
      columns,
      visible: false,
      file: 'https://img.bzhz.jnbygroup.com/box%E5%8F%91%E5%88%B8%E6%A8%A1%E6%9D%BF.xls',
      labelCol: { span: 4 },
      wrapperCol: { span: 14 },
      form: {},
      headers: {
        authorization: 'authorization-text'
      },
      fileList: [],
      uploadParams: {},
      formKeyData: {},
      rules: {
        innerName: [{ required: true, message: '请输入', trigger: 'blur' }],
        name: [{ required: true, message: '请输入', trigger: 'blur' }],
        type: [{ required: true, message: '请选择', trigger: 'change' }],
        sendTime: [{ required: true, message: '请选择', trigger: 'change' }],
        noticeType: [{ required: true, message: '请选择', trigger: 'change' }],
        sendType: [{ required: true, message: '请选择', trigger: 'change' }]
      },
      uploadHost: '',
      couponsList: [],
      showTip: false,
      showTipClient: false,
      fileSize: 1,
      sms: '你在【${coupon_name}】活动中 收到【${num}】张【${amount}】券已到账！'
    }
  },
  computed: {},
  created() {
    this.uploadParams = { ...globalData.uploadParams }
    this.uploadHost = this.uploadParams.uploadHost
  },
  mounted() {},
  methods: {
    show(str) {
      if (str != 'add') {
        this.form = str
        this.form.sendTime = moment(str.sendTime)
        let couponIds = this.form.couponId.split(',')
        this.fetchCurrentCoupons(couponIds)
      } else {
        this.form = {
          userFileUrl: '',
          innerName: '',
          name: '',
          type: '',
          sendTime: null,
          noticeType: '',
          sendType: ''
        }
      }
      this.fetchUploadToken()
      this.visible = true
    },
    onClose() {
      this.$refs.ruleForm.resetFields()
      this.$emit('editOk')
      this.showTip = false
      this.showTipClient = false
      this.couponsList = []
      this.fileList = []
      this.visible = false
    },
    // 回显券
    fetchCurrentCoupons(list) {
      let params = {
        requestData: {
          ruleIds: list
        },
        page: {
          pageNo: 1,
          pageSize: 100
        }
      }
      couponList(params).then(res => {
        if (res.code == 0) {
          this.couponsList = res.data
        } else {
          this.$message.warning(res.msg)
        }
      })
    },
    openCoupons() {
      this.$refs.couponModal.show()
    },
    fetchUploadToken() {
      uploadToken().then(res => {
        if (res.code == 0) {
          this.token = res.data
        } else {
          this.$message.warning(res.msg)
        }
      })
    },
    // 导入
    beforeUpload(file) {
      const isLt2M = file.size / 1024 / 1024 < this.fileSize
      if (!isLt2M) {
        this.$message.error(`文件请小于${this.fileSize}MB!`)
        return new Promise((resolve, reject) => {
          reject()
        })
      }
      if (this.isMultiple) {
        this.fileList = [...this.fileList, file]
      } else {
        this.fileList = [file]
      }

      const key = new Date().getTime() + '-' + file.name
      this.formKeyData = {
        key: key,
        token: this.token
      }
      return true
    },
    handleChange(info) {
      let fileList = []
      fileList = [...info.fileList]
      if (info.file.status !== 'uploading') {
        // console.log(info.file, info.fileList)
      }
      if (info.file.status === 'done') {
        // console.log('success', fileList)
        let list = fileList.map(file => {
          if (file.response) {
            file.url = this.uploadHost + file.response.key
          }
          return file.url
        })
        // console.log(list)
        this.form.userFileUrl = list[0]
      } else if (info.file.status === 'error') {
        this.$message.error(`${info.file.name} file upload failed.`)
      }
    },
    handleRemove(file) {
      const index = this.fileList.indexOf(file)
      const newFileList = this.fileList.slice()
      newFileList.splice(index, 1)
      this.fileList = newFileList
    },
    // 下拉框搜索
    filterOption(input, option) {
      return option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
    },
    handleAddCoupons(list) {
      let coupons = [...this.couponsList, ...list]
      let newArr = coupons.filter((currentValue, currentIndex, sourceArr) => {
        return sourceArr.findIndex(x => x.id === currentValue.id) === currentIndex
      })
      this.couponsList = newArr
    },
    handleDeleteProduct(index) {
      this.couponsList.splice(index, 1)
    },
    onSubmit() {
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          if (this.couponsList.length == 0) {
            this.showTip = true
            return false
          }
          if (!this.form.userFileUrl) {
            this.showTipClient = true
            return false
          }
          this.showTip = false
          this.showTipClient = false
          let formValue = JSON.parse(JSON.stringify(this.form))
          formValue.sendTime = this.form.sendTime.format('YYYY-MM-DD HH:mm:ss')
          let couponIdArr = this.couponsList.map(e => e.id)
          formValue.couponId = couponIdArr.join(',')
          console.log(formValue)
          let params = {
            requestData: formValue
          }
          createSendCoupon(params).then(res => {
            if (res.code == 0) {
              this.$message.success('保存成功！')
              this.$emit('editOk')
              this.onClose()
            } else {
              this.$message.warning(res.msg)
            }
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    resetForm() {
      this.$refs.ruleForm.resetFields()
    }
  }
}
</script>

<style lang="less" scoped>
.tip {
  color: #f5222d;
  line-height: 22px;
  margin-top: 8px;
}
</style>

